import router, { asyncRoutes } from './router'
import store from './store'
import { Form, Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    // console.log("ins"+store.getters.ins);
    // if (to.path === '/choose' || to.path === '/projectAdd') {
    //   console.log(from.path+"-----to-------" + to.path);
    //   if(store.getters.ins == 2) {
    //     next()
    //   }

    //   // else{
    //   //   next({path: '/'})
    //   // }
    // } else 
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      store.dispatch('LogOut').then(() => {
        location.reload() // 为了重新实例化vue-router对象 避免bug
      })

      // if(store.getters.ins == 1) {
      //   next({ path: '/' })
      // } else {
      //   next({ path: '/choose' })
      // }
      
      NProgress.done()
    } else {
      // determine whether the user has obtained his permission roles through getInfo
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          // get user info
          // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
          const { roles } = await store.dispatch('GetInfo')

          // generate accessible routes map based on roles
          const accessRoutes = await store.dispatch('permission/generateRoutes', store.state.user.category)
          // console.log('access'+JSON.stringify(accessRoutes));

          // dynamically add accessible routes
          router.addRoutes(accessRoutes)
  
          if(store.getters.ins == 2 && from.path == '/login') {
            next({ path: '/choose' })
          } else if(store.getters.ins == 1 && from.path == '/login'){
            next({path: '/'})
          } else {
            next({ ...to, replace: true })
          }

          
        } catch (error) {
          // remove token and go to login page to re-login
          //await store.dispatch('FedLogOut')
          Message.error({message:error || '登陆失败'})
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
